//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package comment_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/project_comment_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type UnReadInfoDbItem struct {
	UnReadId   string `bson:"_id"`
	ProjectId  string `bson:"projectId"`
	UserId     string `bson:"userId"`
	TargetType uint32 `bson:"targetType"`
	TargetId   string `bson:"targetId"`
	TimeStamp  int64  `bson:"timeStamp"`
}

func (item *UnReadInfoDbItem) ToUnReadInfo() *project_comment_api.UnReadInfo {
	return &project_comment_api.UnReadInfo{
		TargetType: project_comment_api.COMMENT_TARGET_TYPE(item.TargetType),
		TargetId:   item.TargetId,
	}
}

type _UnReadDao struct {
	mc *mongo.Collection
}

func newUnReadDao(db *mongo.Database) (*_UnReadDao, error) {
	mc := db.Collection(db_ns.DB_NS_COMMENT + "unread")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"projectId", 1}, {"userId", 1}, {"timeStamp", -1}},
		},
		{
			Keys: bson.D{{"projectId", 1}, {"targetId", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_UnReadDao{mc: mc}, nil
}

func (db *_UnReadDao) Insert(ctx context.Context, dbItem *UnReadInfoDbItem) error {
	dbItem.UnReadId = db.genUnReadId(dbItem.ProjectId, dbItem.UserId, dbItem.TargetId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_UnReadDao) genUnReadId(projectId, userId, targetId string) string {
	return fmt.Sprintf("%s:%s:%s", projectId, userId, targetId)
}

func (db *_UnReadDao) Exist(ctx context.Context, projectId, userId string, targetType uint32, targetId string) (bool, error) {
	unreadId := db.genUnReadId(projectId, userId, targetId)
	count, err := db.mc.CountDocuments(ctx, bson.M{
		"_id":        unreadId,
		"targetType": targetType,
	})
	return count > 0, err
}

func (db *_UnReadDao) Remove(ctx context.Context, projectId, userId string, targetType uint32, targetId string) error {
	unreadId := db.genUnReadId(projectId, userId, targetId)
	_, err := db.mc.DeleteOne(ctx, bson.M{
		"_id":        unreadId,
		"targetType": targetType,
	})
	return err
}

func (db *_UnReadDao) RemoveByTarget(ctx context.Context, projectId string, targetType uint32, targetId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{
		"projectId":  projectId,
		"targetType": targetType,
		"targetId":   targetId,
	})
	return err
}

func (db *_UnReadDao) RemoveByUser(ctx context.Context, projectId, userId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{
		"projectId": projectId,
		"userId":    userId,
	})
	return err
}

func (db *_UnReadDao) Get(ctx context.Context, projectId, userId string, targetType uint32, targetId string) (*UnReadInfoDbItem, error) {
	retItem := &UnReadInfoDbItem{}
	unreadId := db.genUnReadId(projectId, userId, targetId)
	err := db.mc.FindOne(ctx, bson.M{
		"_id":        unreadId,
		"targetType": targetType,
	}).Decode(retItem)
	return retItem, err
}

func (db *_UnReadDao) Count(ctx context.Context, projectId, userId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{
		"projectId": projectId,
		"userId":    userId,
	})
	return uint32(count), err
}

func (db *_UnReadDao) List(ctx context.Context, projectId, userId string, offset, limit int64) ([]*UnReadInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{
		"projectId": projectId,
		"userId":    userId,
	}, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*UnReadInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_UnReadDao) RemoveCicdTarget(ctx context.Context) error {
	// COMMENT_TARGET_CI_CD = 4;         // CI/CD(废弃)
	_, err := db.mc.DeleteMany(ctx, bson.M{
		"targetType": 4,
	})
	return err
}

func (db *_UnReadDao) RemoveApiCollTarget(ctx context.Context) error {
	// COMMENT_TARGET_API_COLL = 5;      // API集合
	_, err := db.mc.DeleteMany(ctx, bson.M{
		"targetType": 5,
	})
	return err
}
